package com.wjm.controller;


import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;


@Controller
public class ImgUploadController {
    @RequestMapping(value = "/imgUpload",method = RequestMethod.POST)
    @ResponseBody
    public String uploadImg(  MultipartFile upfile) {
        System.out.println("文件上传中---------");
        String path = getPath(upfile);

        //默认需要回调的json格式
        String config =
                "{\n" +
                        "            \"state\": \"SUCCESS\",\n" +
                        "                \"url\": \"http://localhost:8081/upload/"+path+"\",\n" +
                        "                \"title\": \"path\",\n" +
                        "                \"original\": \"path\"\n" +
                        "        }";

        return  config;

    }
    
    public String getPath(MultipartFile file){

        if (file.isEmpty()) {
            return "文件不能为空";
        }
        // 获取文件名
        String fileName = file.getOriginalFilename();
        System.out.println("上传的文件名为：" + fileName);
        // 获取文件的后缀名
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        System.out.println("上传的后缀名为：" + suffixName);
        // 文件上传后的路径
        String filePath = "D:\\";
        // 解决中文问题，liunx下中文路径，图片显示问题
        // fileName = UUID.randomUUID() + suffixName;
        File dest = new File(filePath + fileName);
        // 检测是否存在目录
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }
        try {
            file.transferTo(dest);
            return "文件成功";
        }catch (IOException e) {
            e.printStackTrace();
        }
        return  dest.getPath();
    }
    

}
